package com.aokang.footwear.common.serializer;

import com.aokang.footwear.common.enums.ErrorCodeEnum;
import com.aokang.footwear.common.exception.BaseServiceException;
import com.aokang.footwear.common.utils.MyDateUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author chil
 * @date 2023/6/19
 * 时间格式序列化、反序列化
 */
@JsonComponent
public class MyDateSerializer {

    // 序列化
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @SneakyThrows
        @Override
        public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider serializers) {
            generator.writeString(value.format(MyDateUtil.Y_MM_DD_HH_MM_SS));
        }
    }

    public static class LocalDateSerializer extends JsonSerializer<LocalDate> {
        @SneakyThrows
        @Override
        public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider serializers) {
            generator.writeString(value.format(MyDateUtil.Y_M_D));
        }
    }

    // 反序列化
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext ctx) {
            try {
                String value = jsonParser.getText();
                if (StringUtils.isNotBlank(value)) {
                    return MyDateUtil.toLocalDateTime(value);
                }
            } catch (IOException e) {
                throw new BaseServiceException(ErrorCodeEnum.TIME_FORMAT_ERROR);
            }
            return null;
        }
    }

    public static class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
        @Override
        public LocalDate deserialize(JsonParser jsonParser, DeserializationContext ctx) {
            try {
                String value = jsonParser.getText();
                if (StringUtils.isNotBlank(value)) {
                    return MyDateUtil.toLocalDate(value);
                }
            } catch (IOException e) {
                throw new BaseServiceException(ErrorCodeEnum.TIME_FORMAT_ERROR);
            }
            return null;
        }
    }
}

